<script src="{{ getAssets }}js/autocompleter/jquery.autocomplete.min.js?v={{ assets_version }}"></script>
<script>
var optometryData;  //保存配镜数据
function receiveFormData(d) {
	if(!d) return false;
	
	if(d.isProduct == 1) {
		receiveFormDataProduct(d);
	} else {
		for (var key in d){
			 val = d[key]
			 if(key == "Sex") {
				 $('input[name="Sex"]').each(function(){ if($(this).attr("value") == val) { $(this).prop("checked", true) }  });
			 }else if(key =="address") {
				 
			 }else{
				$("#"+key).val(val)
			 }
		 }
		 $('select').trigger('changed.selected.amui');
		 formValidatorReset('formDoSubmitDialogPay');
	}
}

var total_row_id = 0;
var now_rows = 0;
var select_rows = 0;  //选择的行

$('#addgroup').click(function(){  //添加一组
	appendTableRow(3);
});
$('#addone').click(function(){  //添加一个
	appendTableRow(1);
});

function appendTableRow(addnum) {
	if(!addnum) {
		addnum = 1;	
	}
	for(i=1;i<=addnum;i++) {
		now_rows += 1;
		rowHtml = '<tr id="row_'+now_rows+'"><td style="text-align:center;">';
		rowHtml += '<input type="hidden" class="rm" value="'+now_rows+'" />';
		rowHtml += '<a href="javascript:void(0);" class="reduce_one"><i class="am-icon-minus"></i></a></td>';
		if(addnum>1) { //表示成组添加
			if(i==1) {
				rowHtml += '<td><input type="hidden" id="eye_type_'+now_rows+'" name="eye_type[]" value="R" /><input type="text" value="R"  readonly /></td>';
			}else if(i==2){
				rowHtml += '<td><input type="hidden" id="eye_type_'+now_rows+'" name="eye_type[]" value="L" /><input type="text" value="L"  readonly /></td>';
			} else {
				rowHtml += '<td><input type="text" id="eye_type_'+now_rows+'" value="" name="eye_type[]"  readonly /></td>';
			}
		} else {
			rowHtml += '<td><input type="text" value="" name="eye_type[]"  readonly /></td>';	
		}
		rowHtml += '<td><input type="hidden" name="inventory_id[]" id="inventory_id_'+now_rows+'" value="" /><input type="hidden" name="product_id[]" id="product_id_'+now_rows+'" class="product_id" value="" /><input type="text" name="product_name[]" data-rows="'+now_rows+'" class="select_product" id="product_name_'+now_rows+'" autocomplete="off" value="" /></td>';
		rowHtml += '<td><input type="text" class="glasses" id="diopter_'+now_rows+'" name="diopter[]"  readonly /></td>';  //屈光度
		rowHtml += '<td><input type="text" class="glasses" id="astigmatism_'+now_rows+'" name="astigmatism[]"  readonly /></td>';  //散光度
		rowHtml += '<td><input type="text" id="model_number_'+now_rows+'" name="model_number[]"  readonly /></td>';  //规格
		rowHtml += '<td><input type="text" id="colour_number_'+now_rows+'" name="colour_number[]" readonly /></td>';  //色号
		rowHtml += '<td><input type="text" name="amount[]" id="product_amount_'+now_rows+'" class="amount" onkeyup="calculate()" value="1"/></td>';  //产品数量
		rowHtml += '<td><input type="text" name="original_price[]" id="product_original_price_'+now_rows+'" value="" readonly="readonly"/></td>'; //产品原价
		rowHtml += '<td><input type="text" name="discount_rate[]" id="product_discount_rate_'+now_rows+'"value="100"  readonly="readonly"/></td>';
		rowHtml += '<td><input type="text" name="unit_price[]" id="product_unit_price_'+now_rows+'" class="unit_price"  onkeyup="calculate()"/></td>'; //实售价格
		rowHtml += '<td><input type="text" name="total_price[]" id="product_total_price_'+now_rows+'" class="total_price" readonly="readonly" /></td>';  //总金额
		rowHtml += '</tr>';
		$('#add_products').append(rowHtml);
	}
	$('.select_product').keydown(function(event){
		if (event.keyCode == 13) {
          	var keyword = $(this).val();
			if(keyword == '') {
				return false;	
			}
			select_rows = $(this).data('rows'); //获取当前行
			eye_type = $('#eye_type_'+select_rows).val();
			
			var dr = '';  //屈光度
			var am = '';  //散光度

			if(optometryData && eye_type != '') {
				if($('#is_yuan').prop('checked')) {
					dr = eye_type == 'R' ? optometryData.RYuanYongMap.qiu_jing : optometryData.LYuanYongMap.qiu_jing;
					am = eye_type == 'R' ? optometryData.RYuanYongMap.zhu_jing : optometryData.LYuanYongMap.zhu_jing;
				} else if($('#is_jin').prop('checked')) {
					dr = eye_type == 'R' ? optometryData.RJingYongMap.qiu_jing : optometryData.LJingYongMap.qiu_jing;
					am = eye_type == 'R' ? optometryData.RJingYongMap.zhu_jing : optometryData.LJingYongMap.zhu_jing;
				}
			}
			//console.log(optometryData);
			//console.log(dr+"====="+am);
			if(dr == '0.00') {
				dr = '-0.00';	
			}else if(dr && dr.indexOf('-') == -1) {
				dr = '+' + dr.replace("+",'');
			}
			
			if(am == '0.00') {
				am = '-0.00';	
			}else if(am && am.indexOf('-') == -1) {
				am = '+' + am.replace("+",'');
			}

            dr = encodeURIComponent(dr);
            am = encodeURIComponent(am);

		  	var url = '{{ urlfor "InventoryController.SelectInventory"}}?query_keyword='+keyword+'&query_dr='+dr+'&query_am='+am+'&eye_type='+eye_type;
			layer.open({
				type: 2,
				title: '选择产品',
				shadeClose: false,
				shade: 0.2,
				maxmin: true,
				shift: 1,
				area: ['95%', '90%'],
				content: url
			});
			return false;
		  
        }
	});
	
}

//减少一条信息
$(document).on('click','.reduce_one',function(){
	var row_id = $(this).parent().parent().attr('id');
	//如果行内存在商品，弹出操作提示
	row_val = row_id.substr(4);
	if($('#product_id_'+row_val).val() == ''){
		$('#'+row_id).remove();
		calculate();
	}else{
		if(confirm('该行存在商品，确定要移除么？')){
			$('#'+row_id).remove();
			calculate();
		}else{
			return false;
		}
	}
	// now_rows --;
});
<!-- 增加和减少ROW END-->
function receiveFormDataProduct(data) {
	
	if(data.Inventory<=0 && !confirm("该产品库存小于0，是否继续添加！")) {
		return false;
	}

	
	var product_id = data.Products.Id;
	var product_name = data.ProductName
	var standard = data.Products.Standard
	var suggested_price = 0;
	var original_price = data.Products.SuggestedPrice;
	var diopter = data.Diopter;
	var astigmatism = data.Astigmatism;
	var model_number = data.ModelNumber;
	var colour_number = data.ColourNumber;
	var inventory_id = data.Id;
	
	$('#inventory_id_'+select_rows).val(inventory_id); //库存ID
	$('#product_id_'+select_rows).val(product_id); //产品ID
	$('#product_name_'+select_rows).val(product_name); //产品名称
	$('#diopter_'+select_rows).val(diopter);  //屈光度
	$('#astigmatism_'+select_rows).val(astigmatism); //散光度
	$('#model_number_'+select_rows).val(model_number); //规格
	$('#colour_number_'+select_rows).val(colour_number); //色号
	$('#product_original_price_'+select_rows).val(original_price);  //产品原价
    $('#product_unit_price_'+select_rows).val(original_price);  //实售价格
	calculate();
}


$(function(){
	appendTableRow(3); //初始增加3个
});

$('#is_customized').change(function(){
	if($(this).prop('checked')) {  //确定要定制
		$('.glasses').attr('readonly', false).attr('required', true);
			
	} else {
		$('.glasses').attr('readonly', true).attr('required', false);	
	}
});


{{if eq .optid 0}}
$('#Mobile').blur(function(){
	if($(this).val() == '') {
		return false;	
	}
	$.post('{{urlfor "ArchivesController.SelectArchives"}}', {"keyword":$(this).val()}, function(j){
		if (j.code == 1) {
			searcharchives()	
		}
	}, 'json')  
});
{{else}}

$(function(){
	var index = layer.load(0, {shade: false});
	$.post('{{urlfor "OptometryController.ViewOne"}}/{{.optid}}', function(j){
		layer.close(index);
		if(j.code == 1) {
			layer.msg(j.msg);
			return false;
		}
		optometryData = j.data;
		receiveFormData(optometryData.Archives);
		
		$('#optometry_id').val(optometryData.Id);
	},'json');
});

{{end}}

$("#searcharchives").click(function(){
	searcharchives();
});  
  
$('#windowOut').click(function(){
	parent.layer.closeAll('iframe');
});
$('#business_id').on('change', function(){
	$('#BusinessName').val($(this).find(':selected').text())
});

$('#formDoSubmitDialogPay').click(function(){
	var formValidity = $('#formDoSubmitDialogPayForm').validator('isFormValid');
	if(formValidity) { //通过检查
		if(confirm('确定保存吗？')){
			$.post('{{ urlfor "RetailController.AddSales"}}', $('#formDoSubmitDialogPayForm').serialize(), function(j){
				if(j.code == 1) {
					layer.msg(j.msg);
				} else {
					layer.msg('保存成功');
					setTimeout(function(){
						location.reload();
					}, '2000');
				}
			},'json');
		}
	}
	return false;	
});


function searcharchives() {
	key = $("#Mobile").val();
	layer.open({
        type: 2
        , skin: 'layui-layer-molv'
        , title: '<i class="fa fa-cog"></i>&nbsp;查找资料'
        , shadeClose: true
        , shade: 0.2
		, moveOut : true
        , id: 'search_archives_dialog'
        , area: ['95%', '95%']
        , content: ['{{urlfor "ArchivesController.SelectArchives"}}?keyword=' + key]
        , anim: 1 //动画类型
		, zIndex: layer.zIndex
		,success: function(layero){
			//console.log(layero)
		    layer.setTop(layero);
		}
    });
}

<!-- 根据选项计算价格 -->
function calculate(){
	for(param=1;param<=now_rows;param++) {
		if($('#product_id_'+param).val() != '' && $('#product_id_'+param).val() != '0'){
			//先对当前Row进行计算
			var amount = $('#product_amount_'+param).val();  //产品数量
			var original_price = $('#product_original_price_'+param).val();  //产品原价
            var unit_price = $('#product_unit_price_'+param).val();  //实售价格
            original_price = new Number(original_price);
            unit_price = new Number(unit_price);

            //计算折扣额
            discount_rate = unit_price / original_price;
            $('#product_discount_rate_'+param).val(discount_rate.toFixed(2));
			//var discount_rate = $('#product_discount_rate_'+param).val();  //产品折扣额%比
			
			//var unit_price = cal_discount_money(original_price, 1, discount_rate);//折扣额计算单价
			//$('#product_unit_price_'+param).val(unit_price);  //产品单价
			
			var total_price = new Number(amount) * new Number(unit_price);// 计算总金额
			$('#product_total_price_'+param).val(total_price.toFixed(2));
			
			
			var total_prime_price = 0.00;
			$('.total_price').each(function(k, v){
				//实际应付总价（不包含其它费用）
				if($(v).val() != '' || $(v).val() != '0.00' || $(v).val() != '0'){
					total_prime_price += new Number($(v).val());
				}
			});
			$('#total_money').val(total_prime_price.toFixed(2));
			cal_discount_price();
		}else{
			continue;
		}
	}
}
<!-- 根据选项计算价格 END-->

<!-- 根据其它费用计算最终应付金额 -->
function cal_discount_price(){
	var total_money = $('#total_money').val();
	var changes_money = $('#changes_money').val();
	
	payment_money = new Number(total_money) - new Number(changes_money);
	$('#payment_money').val(payment_money.toFixed(2));
}
<!-- 根据其它费用计算最终应付金额 END-->

<!-- 计算折扣额 -->
/**
 * 根据原价和折扣率计算出折扣额
 * @unit_price		原价
 * @amount			数量
 * @discount_rate	折扣率
 */
function cal_discount_money(unit_price, amount, discount_rate){
	var product_discount = 0;
	if(discount_rate == 0){
		product_discount = 0;
	}else{
		product_discount = (unit_price * amount) * (discount_rate/100);
	}
	return parseFloat(product_discount).toFixed(2);
}
<!-- 计算折扣额 END-->
//现金付款
function set_cash_money_meter() {
	var cash_money_meter = $('#cash_money_meter').val();  //支付现金
	cash_money_meter = new Number(cash_money_meter);
	var payment_money_meter = $('#payment_money_meter').val();  //须付金额
	payment_money_meter = new Number(payment_money_meter);
	
	var n = 0
	
	$('#arrears_money_meter').val(n);
	$('#give_change_meter').val(n);	
	if(cash_money_meter>=payment_money_meter)  {  //需要计算找零
		n = parseFloat((cash_money_meter - payment_money_meter)).toFixed(2);
		$('#give_change_meter').val(n);	
	} else {  //计算欠款
		n = parseFloat((payment_money_meter - cash_money_meter)).toFixed(2);
		$('#arrears_money_meter').val(n);	
	}
	
	return false;
}

function confirm_pay(t) {
	var payType = $(t).data("pay");
	var cash_money_meter = $('#cash_money_meter').val();  //支付现金
	cash_money_meter = new Number(cash_money_meter);
	
	var payment_money_meter = $('#payment_money_meter').val();  //须付金额
	payment_money_meter = new Number(payment_money_meter);
	
	switch(payType) {
		case 1:break;//刷卡支付
		case 2:break;//微信支付
		case 3:break;//支付宝支付
		case 4:
			if(cash_money_meter == 0) {
				alert('请填写现金支付金额');
				return false;
			}
		break;//现金支付
	}
	$('#payment_type').val(payType);  //设置支付类型
	$('#cash_money').val(cash_money_meter); //设置现金金额
	
	var needMoney = payment_money_meter;
	
	if(cash_money_meter > 0) { //计算支付除现金外支付金额
		needMoney = parseFloat((payment_money_meter - cash_money_meter)).toFixed(2);
	} 
	$('#payment_type_money').val(needMoney);
	
	//开始提交保存数据
	$('.confirm_pay').addClass('am-disabled'); //禁用按钮
	$.post('{{ urlfor "RetailController.AddSales"}}', $('#formDoSubmitDialogPay').serialize(), function(j){
		if(j.code == 1) {
			layer.msg(j.msg);	
			$('.confirm_pay').removeClass('am-disabled'); //取消禁用按钮
		} else {
			if(confirm('保存成功，是否需要打印单据?')) {
				//执行打印尺寸规格210*140
				$.post('{{ urlfor "RetailController.Printer" }}/'+j.data, function(j){
					if(j.code == 1) {
						layer.msg(j.msg);
						return false;	
					}
					createRetailPrinter(j.data);
					setTimeout(function(){
						layer.closeAll();
						location = '/retail/add';
					}, 1000);
				}, 'json');
			} else {
				layer.closeAll();
				location = '/retail/add';
			}
		}
	},'json');
	
	return false;
}
//验光数据
$('#view-optometry').click(function(){
	var opt_id = new Number($('#optometry_id').val());
	var arc_id = new Number($('#Id').val());
	
	if(opt_id == 0 && arc_id == 0) {
		layer.msg('请选择一个客户或验光信息！');
		return false;	
	}
	
	height = "90%";
	layer.open({
		type: 2
		, title: '验光数据'
		, shade: 0.2
		, id: 'viewOptometry_dialog'
		, area: ['96%', height]
		, content: ['{{ urlfor "OptometryController.View"}}?opt_id='+opt_id+'&arc_id='+arc_id]
		, anim: 1 //动画类型
	});
	return false;
});
//历史消费
$('#view-consumption').click(function(){
	
	var opt_id = new Number($('#optometry_id').val());
	var arc_id = new Number($('#Id').val());
	
	if(opt_id == 0 && arc_id == 0) {
		layer.msg('请选择一个客户或验光信息！');
		return false;	
	}
	
	height = "90%";
	layer.open({
		type: 2
		, title: '历史消费'
		, shade: 0.2
		, id: 'viewOptometry_dialog'
		, area: ['96%', height]
		, content: ['{{ urlfor "RetailController.View"}}?opt_id='+opt_id+'&arc_id='+arc_id]
		, anim: 1 //动画类型
	});
	
	return false	
});

</script>